package com.bwie.bwedu.volley;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.bwie.bwedu.utils.LogUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by chenxiangming on 15/8/13.
 */
public class MyRequest {

    public static final int USER_FROM_ANDROID = 0;
    public static final int USER_FROM_IPHONE = 1;

    /**
     * 构造网络请求的head信息
     * @return
     */
    public static String buildHeadJson(Context context){
        Header header = new Header();
        header.device_id = CommonUtil.getDeviceId(context);
        header.from = USER_FROM_ANDROID;
        header.os_vercode = "android" + Build.VERSION.RELEASE;
        header.app_vercode = CommonUtil.getVersionCode(context);
        header.app_vername = CommonUtil.getVersionName(context);
        header.model = Build.MODEL;
        return Jackson.toJson(header);
    }

    private static String parseParamsToString(Map<String, String> params) {
        Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
        StringBuffer sb = new StringBuffer();
        while (it.hasNext()) {
            Map.Entry<String, String> pair = it.next();
            String key = pair.getKey();
            String value = pair.getValue();
            if (!TextUtils.isEmpty(value)) {
                String startStr = sb.length() > 0 ? "&" : "";
                String param = startStr + key + "=" + value;
                sb.append(param);
            }
        }
        return sb.toString();
    }

    /**
     * 异步数据请求
     * @param context
     * @param uri
     * @param paramsMap
     * @param method
     * @param type
     * @param listener
     * @param errorListener
     * @param <T>
     */
    public static <T> void doRequest(Context context, String uri, Map<String, String> paramsMap,int method, Class<T> type, Response.Listener<T> listener, Response.ErrorListener errorListener) {
//        paramEtity.put("common", Jackson.toJson(common));
//        if(paramsMap != null) {
//            paramEtity.put("param", Jackson.toJson(paramsMap));
//        }
//        String params = parseParamsToString(paramEtity);
//    	paramsMap.put("token", SharePrefUtil.readeFromExternal(context, SharePrefUtil.USER_TOKEN,""));       
    	String params = parseParamsToString(paramsMap);
        LogUtils.d("url--->" + uri);
        LogUtils.d("params--->" + params);


        if (method == Request.Method.GET && !TextUtils.isEmpty(params)) {
            if (uri.contains("?")) {
                uri += "&" + params;
            } else {
                uri += "?" + params;
            }
            params = "";
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuffer sb = new StringBuffer(sdf.format(new Date())).append("------->").append("\n");

        try{
            sb.append(uri).append("\n");
            sb.append(params).append("\n");
        }catch(Exception e){
            e.printStackTrace();
        }

        MyJsonRequest<T> request = new MyJsonRequest<T>(context,method, uri, params, type, listener, errorListener);
        try {
            request.getHeaders().put("device", buildHeadJson(context));
//            String sessionId = SharePrefUtil.readeFromExternal(UIUtils.getContext(), SharePrefUtil.USER_TOKEN, "");
           String sessionId = "";
            if(!TextUtils.isEmpty(sessionId)){
            	request.getHeaders().put("Cookie", "JSESSIONID=" + sessionId);
            }
            LogUtils.d("header --->" + buildHeadJson(context));
        } catch (AuthFailureError authFailureError) {
            authFailureError.printStackTrace();
        }
        HttpManager.getInstance(context).addToRequestQueue(request);
    }

}
